package com.orange.wwwapi.controller.oss;

import com.orange.core.pojo.R;
import com.orange.core.pojo.entity.oss.OssFile;
import com.orange.core.pojo.rsp.oss.OssUploadRsp;
import com.orange.core.service.oss.OssFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * 文件上传下载
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/file")
public class OssController {

    private final OssFileService ossFileService;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return 文件地址
     */
    @PostMapping("/upload")
    public R<OssUploadRsp> upload(@RequestParam("file") MultipartFile file) throws IOException {
        return R.ok(ossFileService.uploadFile(file.getInputStream(), file.getOriginalFilename()));
    }

    /**
     * 文件下载
     *
     * @param filename 文件名
     */
    @GetMapping("/download/{filename}")
    public ResponseEntity<byte[]> download(@PathVariable String filename) {
        OssFile ossFile = ossFileService.getByFilename(filename);
        if (ossFile == null) {
            throw new IllegalArgumentException("文件不存在");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(ossFile.getFilename(), Charset.defaultCharset()));
        return new ResponseEntity<>(ossFile.getObject(), headers, HttpStatus.CREATED);
    }
}
